const app = getApp();
const host = app.globalData.host;
var self = null;

Page({
  data: {
    swiper: {
      current: 0,
      previousmargin: "30rpx",
      nextMargin: "30rpx"
    },
    navH: null,
    fromOutside: false,

    itemId: '',
    productId: '',
    groupId: '',
    shareGroupId: '',
    info: {},
    imageList: [],
    paidUsers: [],
    gallery: [],

    formats: '',
    selectedFormatId: '',
    selectedFormat: '',
    selectedPrice: '',
    popupVisible: false,

    hidePage: true,
    latlng: ''
  },
  onLoad(options) {
    self = this;
    self.setData({
      navH: app.globalData.navHeight
    })
    if (options.q) {
      if (decodeURIComponent(options.q).indexOf('?') < 0) {
        wx.showModal({
          title: '提示',
          content: '二维码无效',
          confirmText: '返回首页',
          showCancel: false,
          success: obj => {
            wx.reLaunch({
              url: '/pages/index/index'
            })
          }
        })
        return;
      }
      var q = decodeURIComponent(options.q);
      var paramStr = q.split('?')[1];
      var paramArray = paramStr.split('&');
      var params = {};
      for (var i = 0; i < paramArray.length; i++) {
        var param = paramArray[i].split('=');
        params[param[0]] = param[1] ? param[1] : '';
      }
      console.log(q);
      console.log(params);
      self.setData({
        productId: params.productId
      })
    }
    if (options.itemId) {
      self.setData({
        itemId: options.itemId
      })
    }
    if (options.productId) {
      self.setData({
        productId: options.productId
      })
    }
    if (options.groupId) {
      self.setData({
        shareGroupId: options.groupId
      })
    }
    // if (options.fromOutside) {
    //   self.setData({
    //     fromOutside: true
    //   })
    // }
    if (getCurrentPages().length == 1) {
      self.setData({
        fromOutside: true
      })
    }
    if (wx.getStorageSync("openId")) {
      self.init();
    } else { // 若进入商品详情页app.js的wx.login网络请求尚未结束，设置回调待执行
      app.wechatLoginCallback = function () {
        self.init();
        app.wechatLoginCallback = null;
      }
    }
  },
  init() {
    var url = null;
    var params = null;
    if (self.data.itemId) {
      url = host + '/yq/item/info'
      params = {
        itemId: self.data.itemId
      }
    } else if (self.data.productId) {
      url = host + '/yq/product/info'
      params = {
        productId: self.data.productId
      }
    }
    var success = function (res) {
      console.log(res);
      if (res.info.item && res.info.item.url) {
        wx.redirectTo({
          url: '/pages/web/web?url=' + res.info.item.url + '&itemId=' + res.info.item.id + '&shareTitle=' + res.info.item.shareTitle + '&shareImage=' + res.info.item.shareImage
        })
        return;
      }
      if ((res.info.item && res.info.item.groupId) || (res.info.product && res.info.product.groupId)) {
        self.setData({
          groupId: (res.info.item && res.info.item.groupId) ? res.info.item.groupId : res.info.product.groupId
        })
      }
      if (res.info.product && res.info.product.formats) {
        self.setData({
          // formats: JSON.parse(res.info.product.formats)
          formats: res.info.product.formats
        })
      }
      self.setData({
        info: res.info,
        hidePage: false
      })
      if ((self.data.info.item && self.data.info.item.images) || (self.data.info.product && self.data.info.product.images)) {
        var imageList;
        if (self.data.info.item && self.data.info.item.images) {
          imageList = self.data.info.item.images.split(";");
        } else if (self.data.info.product && self.data.info.product.images) {
          imageList = self.data.info.product.images.split(";");
        }
        imageList.pop();
        if (imageList.length != 0) {
          self.setData({
            imageList: imageList
          })
        }
      }
      if (self.data.info.product && self.data.info.product.paidUsers) {
        var paidUsers = self.data.info.product.paidUsers.split(";");
        paidUsers.pop();
        if (paidUsers.length != 0) {
          self.setData({
            paidUsers: paidUsers
          })
        }
      }
      if (self.data.info.item && self.data.info.item.gallery) {
        var gallery = self.data.info.item.gallery.split(";");
        gallery.pop();
        self.setData({
          gallery: gallery
        })
      }
      if (self.data.info.product.latlng) {
        var latlng = self.data.info.product.latlng.split(',');
        self.setData({
          latlng: latlng
        })
      }
    };
    var fail = function (res) { };
    var complete = function () { };
    app.request(url, params, success, fail, complete);

    // 由分享链接进入参团
    // var obj = wx.getLaunchOptionsSync();
    // console.log(obj);
    // if (self.data.groupId) {
    //   var url = host + '/yq/group/join'
    //   var params = {
    //     groupId: self.data.groupId
    //   }
    //   var success = function(res) {
    //     wx.showToast({
    //       title: '参团成功',
    //       icon: 'none'
    //     })
    //   };
    //   var fail = function(res) {};
    //   var complete = function() {};
    //   app.request(url, params, success, fail, complete);
    // }
  },
  invite(e) {
    if (self.data.groupId) {
      wx.navigateTo({
        url: '/pages/pintuan/pintuan?itemId=' + self.data.itemId + '&productId=' + self.data.productId + '&groupId=' + self.data.groupId
      })
    // } else {
    //   wx.navigateTo({
    //     url: '/pages/pintuan/pintuan?itemId=' + self.data.itemId + '&productId=' + self.data.productId
    //   })
    }
  },
  selectFormat(e) {
    self.setData({
      popupVisible: true
    })
  },
  hideFormat(e) {
    self.setData({
      popupVisible: false
    })
  },
  onTapFormat(e) {
    var formatId = e.currentTarget.dataset.formatid;
    var format = e.currentTarget.dataset.format;
    var price = e.currentTarget.dataset.price;
    self.setData({
      selectedFormatId: formatId,
      selectedFormat: format,
      selectedPrice: price
    })
  },
  //定位
  position() {
    wx.getLocation({
      type: 'gcj02', // 返回可以用于wx.openLocation的经纬度
      success(res) {
        const latitude = Number(self.data.latlng[0])
        const longitude = Number(self.data.latlng[1])
        const address = self.data.info.product.address;
        // console.log("latitude", self.data.latlng[0])
        wx.openLocation({
          address: address,
          latitude: latitude,
          longitude: longitude,
          scale: 15,
          success: res => {
            console.log("success", res);
          },
          fail: res=> {
            console.log("fail", res);
          }
        })
      }, fail() {

      }
    })
  },
  goPay(e) {
    if (self.data.info.product.storage == 0) {
      wx.showModal({
        title: '提示',
        content: '补货中',
        showCancel: false
      })
      return;
    }
    if (self.data.info.product.isGroup != 1 && self.data.formats && !self.data.selectedFormatId) {
      wx.showToast({
        title: '请选择规格',
        icon: 'none'
      })
      return;
    }
    // 如果需要填写地址和数量
    // if (self.data.info.product.isNeedMoreInfo === 1) {
    //   wx.navigateTo({
    //     url: '/pages/confirm/confirm?itemId=' + self.data.itemId + '&productId=' + self.data.productId + '&groupId=' + self.data.groupId
    //   })
    //   return;
    // } else if (self.data.info.product.isNeedMoreInfo === 2) {
    //   wx.navigateTo({
    //     url: '/pages/enroll/enroll?itemId=' + self.data.itemId + '&productId=' + self.data.productId + '&groupId=' + self.data.groupId
    //   })
    //   return;
    // } else if (self.data.info.product.isNeedMoreInfo === 3) {

    // } else if (self.data.info.product.isNeedMoreInfo === 4) {
    //   wx.navigateTo({
    //     url: '/pages/extraInfo/extraInfo?itemId=' + self.data.itemId + '&productId=' + self.data.productId + '&groupId=' + self.data.groupId
    //   })
    //   return;
    // }
    self.hideFormat();
    if (self.data.info.product.isNeedMoreInfo != 0) {
      wx.navigateTo({
        url: '/pages/extraInfo/extraInfo?itemId=' + self.data.itemId + '&productId=' + self.data.productId + '&groupId=' + (self.data.shareGroupId ? self.data.shareGroupId : self.data.groupId) + '&formatId=' + self.data.selectedFormatId
      })
      return;
    }

    wx.showLoading({
      title: '提交中',
    })
    var url = host + '/yq/order/pay';
    var data = {
      // name: self.data.name,
      // mobile: self.data.mobile,
      // code: self.data.code,
      // price1Count: self.data.price1Count,
      // price2Count: self.data.price2Count,
      // price3Count: self.data.price3Count,
      // ticketId: self.data.ticketId,
      // size: self.data.selectedFormat,
      formatId: self.data.selectedFormatId
    };
    if (self.data.productId) {
      data.productId = self.data.productId
    }
    if (self.data.itemId) {
      data.itemId = self.data.itemId
    }
    if (self.data.shareGroupId) {
      data.groupId = self.data.shareGroupId;
    } else if (self.data.groupId) {
      data.groupId = self.data.groupId;
    }
    var success = function(res) {
      console.log(res);
      wx.hideLoading()
      var status = res.status
      if (status == 204) {
        wx.showModal({
          title: '出错了',
          content: res.msg
        })
        return;
      }
      var response = res.info
      var nonce_str = response.nonce_str
      var prepay_id = response.prepay_id
      var sign = response.sign
      var timestamp = response.timeStamp
      var appId = response.appid
      var param = {
        'appId': appId,
        'timeStamp': '' + timestamp,
        'nonceStr': '' + nonce_str,
        'package': 'prepay_id=' + prepay_id,
        'signType': 'MD5',
        'paySign': '' + sign,
        'success': function(res) {
          setTimeout(function() {
            wx.navigateTo({
              url: '/pages/success/success?isShowContent=' + 1
            })
          }, 200)

        },
        'fail': function(res) {
          wx.showModal({
            title: '出错了',
            content: '支付失败'
          })
        }
      }
      wx.requestPayment(param);
    };
    var fail = function(res) {};
    var complete = function() {};
    app.request(url, data, success, fail, complete);
  },
  previewImage(e) {
    var urls = new Array;
    var info = self.data.info;
    if ((info.item && info.item.images) || (info.product && info.product.images)) {
      if (info.item.images) {
        urls = info.item.images.split(";");
        urls.pop();
      } else if (info.product.images) {
        urls = info.product.images.split(";");
        urls.pop();
      }
    } else if (info.item && info.item.cover) {
      urls.push(info.item.cover);
    } else if (info.product && info.product.cover) {
      urls.push(info.product.cover);
    }

    if (e.currentTarget.dataset.current) {
      var currentImage = e.currentTarget.dataset.current;
    } else {
      var currentImage = urls[0]
    }
    wx.previewImage({
      urls: urls,
      current: currentImage
    })
  },
  onShareAppMessage(object) {
    if (self.data.itemId) {
      return {
        title: self.data.info.item.shareTitle,
        imageUrl: self.data.info.item.shareImage,
        path: "/" + self.route + "?itemId=" + self.data.itemId
      }
    } else if (self.data.productId) {
      return {
        title: self.data.info.product.shareTitle,
        imageUrl: self.data.info.product.shareImage,
        path: "/" + self.route + "?productId=" + self.data.productId
      }
    }
    return null;
  }
})